package com.leyou.page.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.page.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @date: 2021/4/12 0012 17:41
 * @description: 校验是否有合法token拦截器
 */
@Component
public class AppTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.从请求头中取出token
        String token = request.getHeader(LyConstants.APP_TOKEN_HEADER);

        //2.判断token是否存在
        if (!StringUtils.isEmpty(token)) {
            //拒绝访问
            return false;
        }

        Payload<AppInfo> payload = null;
        //3.校验token是否合法
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), AppInfo.class);
        } catch (Exception e) {
            //拒绝访问
            return false;
        }

        //4.取出token的载荷的目标服务列表
        AppInfo info = payload.getInfo();
        List<String> targetList = info.getTargetList();

        //5.判断当前服务是否在目标服务列表中，在，则放行，不在，拒绝访问
        if (!targetList.contains(jwtProperties.getApp().getServiceName())) {
            return false;
        }

        //6.放行
        return true;
    }
}